package com.wlts.wzy.KSUserModule.controller;


import com.alibaba.fastjson.JSON;
import com.kuaishou.merchant.open.api.KsMerchantApiException;
import com.kuaishou.merchant.open.api.client.AccessTokenKsMerchantClient;
import com.kuaishou.merchant.open.api.client.oauth.OauthAccessTokenKsClient;
import com.kuaishou.merchant.open.api.request.KsMerchantUserSellerGetRequest;
import com.kuaishou.merchant.open.api.response.oauth.KsAccessTokenResponse;
import com.kuaishou.merchant.open.api.response.KsMerchantUserSellerGetResponse;
import com.wlts.wzy.Base.BaseEntity;
import com.wlts.wzy.KSUserModule.entity.KsOauth;
import com.wlts.wzy.KSUserModule.entity.KsStoreUser;
import com.wlts.wzy.KSUserModule.service.IKsOauthService;
import com.wlts.wzy.KSUserModule.service.IKsStoreUserService;
import com.wlts.wzy.Result.Result;
import com.wlts.wzy.api.request.ks.GetMyKsOauthRequest;
import com.wlts.wzy.api.request.ks.UpdateKsUserInfoRequest;
import com.wlts.wzy.configBean.KsConfig.KsConfigInfo;
import com.wlts.wzy.expand.MyLambdaQueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

/**
 * <p>
 * 快手授权信息 前端控制器
 * </p>
 *
 * @author zhiyong
 * @since 2021-02-01
 */
@Api(tags = "快手授权信息 前端控制器")
@RestController
@RequestMapping("/KSUserModule/ks-oauth")
public class KsOauthController {

    @Autowired
    private IKsOauthService ksOauthService;

    @Autowired
    private IKsStoreUserService ksStoreUserService;

    @ApiOperation(value = "获取授权地址")
    @RequestMapping(value = "/getOauthUrl", method = RequestMethod.POST)
    public Result<String> getOauthUrl(@RequestBody GetMyKsOauthRequest request) {

        String url = "https://s.kwaixiaodian.com/oauth/authorize?appId=" + KsConfigInfo.appKey + "&redirect_uri=http://lm.jieerlianqi.cn/lm-ctl/KSUserModule/ks-oauth/saveOauth&scope=user_info,merchant_user,merchant_refund,merchant_order,merchant_logistics,merchant_item&response_type=code&state=" + request.getUserUuid();

        return new Result<>(url);

    }


    @ApiOperation(value = "保存授权")
    @RequestMapping(value = "/saveOauth", method = {RequestMethod.POST, RequestMethod.GET})
    public Result<KsOauth> saveOauth(@RequestParam("code") String code, @RequestParam("state") String state) {

        boolean chageflag = false;

        MyLambdaQueryWrapper<KsStoreUser> wrapper = new MyLambdaQueryWrapper<>();

        wrapper.eq(KsStoreUser::getUuid, state);

        KsStoreUser ksStoreUser = ksStoreUserService.getOne(wrapper);

        if (ksStoreUser == null) {
            return Result.buildResult(500, "用户不存在");
        }

        OauthAccessTokenKsClient oauthAccessTokenKsClient
                = new OauthAccessTokenKsClient(KsConfigInfo.appKey, KsConfigInfo.appSecret);


        try {
            KsAccessTokenResponse response = oauthAccessTokenKsClient.getAccessToken(code);

            if(response.getResult()!=1){
                return Result.buildResult(500, "授权失败 :" + response.getErrorMsg());
            }

            KsMerchantUserSellerGetRequest userSellerGetRequest = new KsMerchantUserSellerGetRequest();
            userSellerGetRequest.setAccessToken(response.getAccessToken());

            AccessTokenKsMerchantClient tokenKsMerchantClient
                    = new AccessTokenKsMerchantClient("", KsConfigInfo.appKey, KsConfigInfo.signSecret);

            KsMerchantUserSellerGetResponse ksMerchantUserSellerGetResponse = tokenKsMerchantClient.execute(userSellerGetRequest);

            if (ksMerchantUserSellerGetResponse.getMerchantUserSellerDataView() != null) {

                MyLambdaQueryWrapper<KsStoreUser> check = new MyLambdaQueryWrapper<>();

                check.eq(KsStoreUser::getKsSellerId, ksMerchantUserSellerGetResponse.getMerchantUserSellerDataView().getSellerId());

                check.eq(BaseEntity::getDelFlag, "0");

                KsStoreUser checkUser = ksStoreUserService.getOne(check);

                if (checkUser != null) {
                    checkUser.setKsName(ksMerchantUserSellerGetResponse.getMerchantUserSellerDataView().getName());
                    checkUser.setKsHead(ksMerchantUserSellerGetResponse.getMerchantUserSellerDataView().getHead());
                    checkUser.setKsSellerId(ksMerchantUserSellerGetResponse.getMerchantUserSellerDataView().getSellerId());
                    state = checkUser.getUuid();
                    ksStoreUserService.updateById(checkUser);
                    chageflag = true;
                } else {
                    ksStoreUser.setKsName(ksMerchantUserSellerGetResponse.getMerchantUserSellerDataView().getName());
                    ksStoreUser.setKsHead(ksMerchantUserSellerGetResponse.getMerchantUserSellerDataView().getHead());
                    ksStoreUser.setKsSellerId(ksMerchantUserSellerGetResponse.getMerchantUserSellerDataView().getSellerId());
                    ksStoreUserService.updateById(ksStoreUser);
                }

            }
            MyLambdaQueryWrapper<KsOauth> queryWrapper = new MyLambdaQueryWrapper<>();
            queryWrapper.eq(KsOauth::getUserUuid, state);
            KsOauth ksOauth = ksOauthService.getOne(queryWrapper);
            if (ksOauth == null) {
                ksOauth = new KsOauth();
            }
            ksOauth.setUserUuid(state);
            ksOauth.setAccessToken(response.getAccessToken());
            ksOauth.setRefreshToken(response.getRefreshToken());
            ksOauth.setExpiresIn(response.getExpiresIn());
            ksOauth.setOpenId(response.getOpenId());
            //access_token过期时间，单位秒，默认为172800，即48小时
            ksOauth.setTokenOverTime(LocalDateTime.now().plusSeconds(response.getExpiresIn()));
            ksOauth.setMessageStatus(0);
            ksOauth.setTokenStatus(0);

            ksOauthService.saveOrUpdate(ksOauth);

            if (chageflag) {
                return Result.buildResult(500, "授权失败：该店铺已授权其他用户！");
            }

            return new Result<>(200,"授权成功",ksOauth);

        } catch (KsMerchantApiException e) {
            e.printStackTrace();
            return Result.buildResult(500, "授权失败");
        }
    }


    @ApiOperation(value = "获取我的授权")
    @RequestMapping(value = "/getMyOauth", method = RequestMethod.POST)
    public Result<KsOauth> getMyOauth(@RequestBody GetMyKsOauthRequest request) {

        MyLambdaQueryWrapper<KsOauth> queryWrapper = new MyLambdaQueryWrapper<>();

        queryWrapper.eq(KsOauth::getUserUuid, request.getUserUuid());

        KsOauth ksOauth = ksOauthService.getOne(queryWrapper);

        return Result.buildResult(ksOauth);

    }


    @ApiOperation(value = "更新商铺信息")
    @RequestMapping(value = "updateStoreInfo", method = RequestMethod.POST)
    public Result<KsStoreUser> updateStoreInfo(@RequestBody UpdateKsUserInfoRequest request) throws KsMerchantApiException {

        MyLambdaQueryWrapper<KsStoreUser> wrapper = new MyLambdaQueryWrapper<>();

        wrapper.eq(KsStoreUser::getUuid, request.getUserUuid());

        wrapper.eq(BaseEntity::getDelFlag, "0");

        //      wrapper.eq(KsStoreUser::getPassword, MD5.md5(request.getPassword()));

        KsStoreUser ksStoreUser = ksStoreUserService.getOne(wrapper);

        if (ksStoreUser == null) {
            return Result.buildResult(500, "用户不存在");
        }
        MyLambdaQueryWrapper<KsOauth> queryWrapper = new MyLambdaQueryWrapper<>();

        queryWrapper.eq(KsOauth::getUserUuid, ksStoreUser.getUuid());

        KsOauth ksOauth = ksOauthService.getOne(queryWrapper);

        if (ksOauth == null) {
            return Result.buildResult(500, "用户未授权");
        }

        KsMerchantUserSellerGetRequest userSellerGetRequest = new KsMerchantUserSellerGetRequest();
        userSellerGetRequest.setAccessToken(ksOauth.getAccessToken());

        AccessTokenKsMerchantClient tokenKsMerchantClient
                = new AccessTokenKsMerchantClient("", KsConfigInfo.appKey, KsConfigInfo.signSecret);

        KsMerchantUserSellerGetResponse response = tokenKsMerchantClient.execute(userSellerGetRequest);

        System.out.println(JSON.toJSONString(response));

        if (response.getMerchantUserSellerDataView() != null) {
            ksStoreUser.setKsName(response.getMerchantUserSellerDataView().getName());
            ksStoreUser.setKsHead(response.getMerchantUserSellerDataView().getHead());
            ksStoreUser.setKsSellerId(response.getMerchantUserSellerDataView().getSellerId());
            ksStoreUserService.updateById(ksStoreUser);
        }

        return Result.buildResult(ksStoreUser);
    }

}
